package shmallarchitect.web.pages;

import java.util.ArrayList;
import java.util.List;
import javax.faces.component.UIComponent;
import javax.faces.component.UIData;
import javax.faces.context.FacesContext;
import javax.faces.event.ActionEvent;
import javax.faces.model.SelectItem;
import shmallarchitect.faces.util.GalleryUtil;
import shmallarchitect.jpa.entities.Gallery;
import shmallarchitect.jpa.entities.User;

public class Main {

    private UIData data = null;
    private Gallery selectedGallery;

    public Gallery getSelectedGallery() {
        return selectedGallery;
    }

    public void setSelectedGallery(Gallery selectedGallery) {
        this.selectedGallery = selectedGallery;
    }

    public Main() {
    }

    public void scroll(int row) {

        int rows = data.getRows();
        if (rows < 1) {
            return;
        }
        if (row < 0) {
            data.setFirst(0);
        } else if (row >= data.getRowCount()) {
            data.setFirst(data.getRowCount() - 1);
        } else {
            data.setFirst(row - (row % rows));
        }

    }

    public void processScrollEvent(ActionEvent event) {
        int currentRow = 1;

        UIComponent component = event.getComponent();
        Integer curRow = (Integer) component.getAttributes().get("currentRow");
        if (curRow != null) {
            currentRow = curRow.intValue();
        }
        scroll(currentRow);
    }

    public List getGalleriesForUser() {
        List galleries;
        User managedUserBean = (User) JSFUtil.getManagedObject("UserBean");
        String login = managedUserBean.getLogin();

        galleries = GalleryUtil.getGalleriesForUser(login);
        JSFUtil.storeOnSession(FacesContext.getCurrentInstance(), "galleries", galleries);

        return galleries;
    }

    public List getGalleryOptions() {
        List<SelectItem> items = new ArrayList<SelectItem>();

        List<Gallery> galleries = (List<Gallery>) JSFUtil.getManagedObject("galleries");
        for(Gallery g : galleries) {
            items.add(new SelectItem(g, g.getName(), g.getCountry() + ", " + g.getCity()));
        }
        return items;
    }

    public void setData(UIData data) {
        this.data = data;
    }

    public UIData getData() {
        return data;
    }
}
